package com.simen.hellobytes.encrypt;

import java.security.*;
import java.security.cert.X509Certificate;

/**
 * @author Created by Simen.
 * @date 创建日期 2018/9/25 08:08
 * @modify 修改者 Simen
 */
public class SignatureUtil {

    /**
     * 生成签名
     *
     * @param data
     * @param signature_algorithm 签名算法,比如MD5withRSA,SHA1withRSA
     * @param privateKey
     * @return 返回签名值
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws SignatureException
     */
    public static byte[] sign(byte[] data, String signature_algorithm, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        Signature signature = Signature.getInstance(signature_algorithm);

        signature.initSign(privateKey);

        signature.update(data);

        return signature.sign();
    }


    /**
     * 验证签名
     *
     * @param data                待效验数据
     * @param sign                数字签名
     * @param signature_algorithm
     * @param publicKey
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws SignatureException
     */
    public static boolean verify(byte[] data, byte[] sign, String signature_algorithm, PublicKey publicKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        Signature signature = Signature.getInstance(signature_algorithm);

        signature.initVerify(publicKey);

        signature.update(data);

        return signature.verify(sign);
    }

    /**
     * 验证签名
     *
     * @param data            待效验数据
     * @param sign            数字签名
     * @param x509Certificate
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws SignatureException
     */
    public static boolean verify(byte[] data, byte[] sign, X509Certificate x509Certificate) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        //由证书构建签名
        Signature signature = Signature.getInstance(x509Certificate.getSigAlgName());
        //由证书初始化签名,实际上是使用了证书的公钥
        signature.initVerify(x509Certificate);

        signature.update(data);

        return signature.verify(sign);
    }


}
